<?php
namespace app\api\controller;

use app\api\model\Applist;
use app\api\model\Elelink;
use app\api\model\Jdorder;
use app\api\model\Userapp;
use app\api\model\Bdwaimai;
use app\index\model\Eleorder;
use ElemeOpenApi\Api\ShopService;
use ElemeOpenApi\Config\Config;
use ElemeOpenApi\OAuth\OAuthClient;

/**
 * Class Index
 * 坚决不用驼峰法
 * @package app\api\controller
 */
class Index
{
    /**
     * 只能使用AJAX访问
     * Index constructor.
     */
    public function __construct()
    {
        if(!request()->isAjax()){
//            die("Error method!");
        }
    }

    /**
     * 空操作
     * @return \think\response\Json
     */
    public function _empty(){
        return json(["code"=>0,"data"=>"","msg"=>"方法不存在"]);
    }

    /**
     * 验证TOKEN
     * @param $token
     * @return bool|mixed
     */
    public static function verifytoken($token){
        $userinfo=model("manager")->where(["token"=>$token])->find();
        if($userinfo){
            return $userinfo["id"];
        }else{
            return false;
        }
    }

    /**
     * 首页框架
     * @return \think\response\View
     */
    public function login()
    {
        $data=\model("manager")->applogin();
		return json($data);
    }

    /**
     * 选择门店列表
     */
    public function selectshop(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $userinfo=model("manager")->where(["id"=>$userid,"type"=>request()->post("usertype")])->find();
            if(!empty($userinfo)&&$userinfo["merchantid"]){
                $shoplist=model("shop")->where(["merchantid"=>$userinfo["merchantid"]])->select();
                return json(["code"=>1,"data"=>$shoplist,"msg"=>"请求成功"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户类型错误"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 自动登录
     * @return \think\response\Json
     */
    public function tokenlogin(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            return json(["code"=>1,"data"=>"","msg"=>"用户TOKEN有效"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一个门店的基本信息
     */
    public function shopinfo(){
        $res=[];
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $shopinfo=model("shop")->where(["id"=>request()->post("shopid")])->find();
        $userid=self::verifytoken(request()->post("token"));
        $userinfo=model("manager")->where(["id"=>$userid])->find();
        $res['shopname']=$shopinfo['shopname'];
        $res['username']=$userinfo['username'];
        if($shopinfo&&$userinfo){
            return json(["code"=>1,"data"=>$res,"msg"=>"请求成功"]);
        }else{
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
    }

    /**
     * 获取该门店的今日营业情况
     */
    public function getincome(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            return json(["code"=>1,"data"=>self::curlorder(request()->post("shopid")),"msg"=>"获取成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一个门店的营业状况
     * @return array
     */
    public static function curlorder($shopid){
        $tlinksdk=new \tlinxsdk();
        $totalpage=0;
        $ttgshopno=model("shop")->where(["id"=>$shopid])->column("ttgshopno");
        if(empty($ttgshopno[0])){
            echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
        }
        $data['page'] = 1; //初始页数
        $data['shop_no'] =$ttgshopno[0];//门店编号
        $data['pagesize']=100; //每页数字
        $data['sdate']=date("Y-m-d");
        $data['edate']=date("Y-m-d");
        $orderlist=[];
        do{
            $result = $tlinksdk->API('order', $data);
            if($result["data"]["pages"]["totalpage"]==0){
                break;
            }
            $data['page']++;
            if($result["errcode"]==1){
                die($result["msg"]);
            }else{
                $orderlist=array_merge($orderlist,$result["data"]["list"]);
                $totalpage=$result["data"]["pages"]["totalpage"];
            }
        }while( $data['page']<=$totalpage);
        return parsedata($orderlist);
    }

    /**
     * 获取最近五天的数据
     */
    public function getnday(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        if(request()->post("pagen")==null){
            $pagen=5;
        }else{
            $pagen=request()->post("pagen");
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $tmp=[];
            for ($i=0;$i<$pagen;$i++){
                $tmp[$i]["date"]=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));//日期
                $totalpage=0;
                $data['page'] = 1; //初始页数
                $data['shop_no'] =$ttgshopno[0];//门店编号
                $data['pagesize']=100; //每页数字
                $data['sdate']=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));
                $data['edate']=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));
                $orderlist=[];
                do{
                    $result = $tlinksdk->API('order', $data);
                    if($result["data"]["pages"]["totalpage"]==0){
                        break;
                    }
                    $data['page']++;
                    if($result["errcode"]==1){
                        echo json_encode(["code"=>0,"data"=>"","msg"=>"系统出现错误!"]);exit();
                    }else{
                        $orderlist=array_merge($orderlist,$result["data"]["list"]);
                        $totalpage=$result["data"]["pages"]["totalpage"];
                    }
                }while( $data['page']<=$totalpage);
                $tmp[$i]["detail"]= parsedata($orderlist);
            }
            return json(["code"=>1,"data"=>$tmp,"msg"=>"获取成功"]);

        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一天的列表
     */
    public function getonelist(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $totalpage=0;
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $data['page'] = 1; //初始页数
            $data['shop_no'] =$ttgshopno[0];//门店编号
            $data['pagesize']=100; //每页数字
            $data['sdate']=request()->post("selectday");
            $data['edate']=request()->post("selectday");
            $orderlist=[];
            do{
                $result = $tlinksdk->API('order', $data);
                if($result["data"]["pages"]["totalpage"]==0){
                    break;
                }
                $data['page']++;
                if($result["errcode"]==1){
                    die($result["msg"]);
                }else{
                    $orderlist=array_merge($orderlist,$result["data"]["list"]);
                    $totalpage=$result["data"]["pages"]["totalpage"];
                }
            }while( $data['page']<=$totalpage);
            return json(["code"=>1,"data"=>$orderlist,"msg"=>"获取成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一个订单的详情
     */
    public function getonedetail(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $totalpage=0;
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $data['page'] = 1; //初始页数
            $data['shop_no'] =$ttgshopno[0];//门店编号
            $data['pagesize']=10; //每页数字
            $data['ord_no']=request()->post("ordno");
            $orderlist=[];
            do{
                $result = $tlinksdk->API('order', $data);
                if($result["data"]["pages"]["totalpage"]==0){
                    break;
                }
                $data['page']++;
                if($result["errcode"]==1){
                    echo json_encode(["code"=>0,"data"=>"","msg"=>"订单不存在!"]);exit();
                }else{
                    $orderlist=array_merge($orderlist,$result["data"]["list"]);
                    $totalpage=$result["data"]["pages"]["totalpage"];
                }
            }while( $data['page']<=$totalpage);
            return json(["code"=>1,"data"=>$orderlist[0],"msg"=>"获取成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }


    /**
     * 获取最近五天的数据
     */
    public function getbill(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        if(request()->post("pagen")==null){
            $pagen=10;
        }else{
            $pagen=request()->post("pagen");
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $tmp=[];
            for ($i=0;$i<$pagen;$i++){
                $tmp[$i]["date"]=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));//日期
                $totalpage=0;
                $data['page'] = 1; //初始页数
                $data['shop_no'] =$ttgshopno[0];//门店编号
                $data['pagesize']=100; //每页数字
                $data['sdate']=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));
                $data['edate']=date("Y-m-d",strtotime("-".(intval(request()->post("count"))+$i)." day"));
                $orderlist=[];
                do{
                    $result = $tlinksdk->API('order', $data);
                    if($result["data"]["pages"]["totalpage"]==0){
                        break;
                    }
                    $data['page']++;
                    if($result["errcode"]==1){
                        echo json_encode(["code"=>0,"data"=>"","msg"=>"系统出现错误!"]);exit();
                    }else{
                        $orderlist=array_merge($orderlist,$result["data"]["list"]);
                        $totalpage=$result["data"]["pages"]["totalpage"];
                    }
                }while( $data['page']<=$totalpage);
                $tmp[$i]["detail"]= parsebill($orderlist);
            }
            return json(["code"=>1,"data"=>$tmp,"msg"=>"获取成功"]);

        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一天的列表(新)
     */
    public function getonebill(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $totalpage=0;
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $data['page'] = 1; //初始页数
            $data['shop_no'] =$ttgshopno[0];//门店编号
            $data['pagesize']=100; //每页数字
            $data['sdate']=request()->post("selectday");
            $data['edate']=request()->post("selectday");
            $orderlist=[];
            do{
                $result = $tlinksdk->API('order', $data);
                if($result["data"]["pages"]["totalpage"]==0){
                    break;
                }
                $data['page']++;
                if($result["errcode"]==1){
                    die($result["msg"]);
                }else{
                    $orderlist=array_merge($orderlist,$result["data"]["list"]);
                    $totalpage=$result["data"]["pages"]["totalpage"];
                }
            }while( $data['page']<=$totalpage);
            return json(["code"=>1,"data"=>["des"=>parsebill($orderlist),"lists"=>$orderlist],"msg"=>"获取成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }


    /**
     *获取指定日期范围的订单
     * 索引数组自动变成关联数组
     */
    public function getbillrange(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $pagen=(strtotime(request()->post("edate"))-strtotime(request()->post("sdate")))/(24*3600);
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $tlinksdk=new \tlinxsdk();
            $ttgshopno=model("shop")->where(["id"=>request()->post("shopid")])->column("ttgshopno");
            if(empty($ttgshopno[0])){
                echo json_encode(["code"=>0,"data"=>"","msg"=>"您尚未绑定TTG门店!"]);exit();
            }
            $tmp=[];
            for ($i=intval($pagen);$i>=0;$i--){
                $tmp[intval($i)]["date"]=date("Y-m-d",strtotime("-".intval($i)." day",strtotime(request()->post("edate"))));//日期
                $totalpage=0;
                $data['page'] = 1; //初始页数
                $data['shop_no'] =$ttgshopno[0];//门店编号
                $data['pagesize']=100; //每页数字
                $data['sdate']=date("Y-m-d",strtotime("-".intval($i)." day",strtotime(request()->post("edate"))));
                $data['edate']=date("Y-m-d",strtotime("-".intval($i)." day",strtotime(request()->post("edate"))));
                $orderlist=[];
                do{
                    $result = $tlinksdk->API('order', $data);
                    if($result["data"]["pages"]["totalpage"]==0){
                        break;
                    }
                    $data['page']++;
                    if($result["errcode"]==1){
                        echo json_encode(["code"=>0,"data"=>"","msg"=>"系统出现错误!"]);exit();
                    }else{
                        $orderlist=array_merge($orderlist,$result["data"]["list"]);
                        $totalpage=$result["data"]["pages"]["totalpage"];
                    }
                }while( $data['page']<=$totalpage);
                $tmp[intval($i)]["detail"]= parsebill($orderlist);
            }
            return json(["code"=>1,"data"=>$tmp,"msg"=>"获取成功"]);

        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取收银员列表
     */
    public function getcashier(){
        if(request()->post("shopid")==null){
            return json(["code"=>0,"data"=>"","msg"=>"门店有误!"]);
        }
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $res=model("Manager")->where(['type'=>2])->where(["shopid"=>request()->post("shopid")])->select();
            return json(["code"=>1,"data"=>$res,"msg"=>"请求成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取一个收银员的详细信息
     */
    public function getonecashier(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $res=model("Manager")->where(['type'=>2])->where(["id"=>request()->post("userid")])->find();
            return json(["code"=>1,"data"=>$res,"msg"=>"请求成功"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }


    /**
     * 修改一个收银员的详细信息
     */
    public function edidonecashier(){
        $userid=self::verifytoken(request()->post("mytoken"));
        $savadate=request()->post();
        unset($savadate["mytoken"]);
        if($userid){
            $res=model("Manager")->where(["id"=>request()->post("id")])->update($savadate);
            if($res){
                return json(["code"=>1,"data"=>$res,"msg"=>"修改成功"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"修改失败"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 增加一个收银员
     */
    public function addonecashier(){
        $userid=self::verifytoken(request()->post("mytoken"));
        $savadate=[];
        $pwd=uniqid();
        $savadate["nickname"]=request()->post("nickname");
        $savadate["username"]=request()->post("username");
        $savadate["password"]=md5($pwd);
        $savadate["authlist"]=request()->post("authlist");
        $savadate["shopid"]=request()->post("shopid");
        $savadate["type"]=2;
        $savadate["status"]=1;
        $manager=model("Manager");
        $manager->data($savadate);
        if($userid){
            $res=$manager->save();
            if($res){

                $data = array('text' => "您的用户名是" . input("post.username").",密码是".$pwd, 'apikey' => \config("yunapikey"), 'mobile' => input("post.username"));
                $json_data = sendsms($data);
                if ($json_data['code'] == 0) {
                    return json(["code"=>1,"data"=>"","msg"=>"增加成功"]);
                } else {
                    return json(["code"=>0,"data"=>"","msg"=>"短信发送失败,请稍后再试"]);
                }
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"增加失败"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 验证码登录
     */
    public function codelogin(){
        $data=\model("manager")->codelogin();
        return json($data);
    }

    /**
     * 发送验证码(需要验证)
     */
    public function sendcode(){
        $userinfo=model("manager")->where(["username"=>request()->post("phone")])->find();
        if(!$userinfo){
            return json(["code"=>0,"data"=>"","msg"=>"手机号不存在"]);
        }else{
            $data = array('text' => "您的验证码是" . input("post.code"), 'apikey' => \config("yunapikey"), 'mobile' => input("post.phone"));
            $json_data = sendsms($data);
            if ($json_data['code'] == 0) {
                return json(["code"=>1,"data"=>"","msg"=>"短信已发送"]);
            } else {
                return json(["code"=>0,"data"=>"","msg"=>"短信发送失败,请稍后再试"]);
            }
        }
    }

    /**
     * 获取百度外卖的详细信息
     */
    public function getbaidu(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $bdmodel=new Bdwaimai();
            $res=$bdmodel->where(["shopid"=>request()->post("shopid")])->find();
            if($res){
                $post_data=[
                    "timestamp"=>time(),
                    "bdshopid"=>$res["bdshopid"]
                ];
                //CURL 拉取远程数据
                $info=curl_post("http://e.xwdcook.com/index.php/Home/Apiv6/getbdone",$post_data);
                return json(["code"=>1,"data"=>json_decode($info,true,512,JSON_BIGINT_AS_STRING),"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"暂无门店"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获得百度门店名称和营业状态
     */
    public function getbdstatus(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $bdmodel=new Bdwaimai();
            $res=$bdmodel->where(["shopid"=>request()->post("shopid")])->find();
            if($res){
                $post_data=[
                    "timestamp"=>time(),
                    "bdshopid"=>$res["bdshopid"]
                ];
                //CURL 拉取远程数据
                $info=curl_post("http://e.xwdcook.com/index.php/Home/Apiv6/getbdstatus",$post_data);
                return json(["code"=>1,"data"=>json_decode($info,true,512,JSON_BIGINT_AS_STRING),"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"暂无门店"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }


    /**
     * 获取百度外卖一天的列表
     * 参数:bdshopid,selectday,token
     */
    public function getbdoneday(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $bdmodel=new Bdwaimai();
            $res=$bdmodel->where(["shopid"=>request()->post("shopid")])->find();
            if($res){
                $post_data=[
                    "timestamp"=>time(),
                    "bdshopid"=>$res["bdshopid"],
                    "selectday"=>!request()->post('selectday')?date("Y-m-d"):request()->post('selectday')
                ];
                //CURL 拉取远程数据
                $info=curl_post("http://e.xwdcook.com/index.php/Home/Apiv6/getbdlist",$post_data);
                return json(["code"=>1,"data"=>json_decode($info,true,512,JSON_BIGINT_AS_STRING),"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"暂无门店"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取百度外卖一天的列表
     * 参数:bdshopid,selectday,token
     */
    public function getbddetail(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $bdmodel=new Bdwaimai();
            $res=$bdmodel->where(["shopid"=>request()->post("shopid")])->find();
            if($res){
                $post_data=[
                    "timestamp"=>time(),
                    "bdshopid"=>$res["bdshopid"],
                    "orderid"=>request()->post('orderid')
                ];
                //CURL 拉取远程数据
                $info=curl_post("http://e.xwdcook.com/index.php/Home/Apiv6/getbddetail",$post_data);
                return json(["code"=>1,"data"=>json_decode($info,true,512,JSON_BIGINT_AS_STRING),"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"暂无门店"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 录入百度外卖门店
     */
    public function addbaidu(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $model=model("Applymsg");
            $model->data([
                "shopid"=>request()->post("shopid"),
                "managerid"=>$userid,
                "createtime"=>date("Y-m-d H:i:s"),
                "detail"=>serialize(["bdshopname"=>request()->post("bdshopname"),"bdshopid"=>request()->post("bdshopid")]),
                "status"=>0
            ]);
            $res=$model->save();
            if($res){
                return json(["code"=>1,"data"=>"","msg"=>"申请成功"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"申请失败,请稍候再试!"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取我的APP列表
     */
    public function getmyapp(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            //获取该门店下的所有可用的APP
            $model=new Userapp();
            $res=$model->getapps(request()->post("shopid"));
            return json(["code"=>1,"data"=>$res,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 购买一个APP
     */
    public function buyapp(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            //获取该门店下的所有可用的APP
            $model=new Userapp();
            $res=$model->buyapp($userid);
            if($res){
                return json(["code"=>1,"data"=>$res,"msg"=>"购买成功"]);
            }else{
                return json(["code"=>0,"data"=>$res,"msg"=>"购买失败"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取APP的详情
     */
    public function getappdetail(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            //获取该门店下的所有可用的APP
            $model=new Applist();
            $res=$model->querydetail(request()->post("shopid"),request()->post("appid"));
            if($res){
                return json(["code"=>1,"data"=>$res,"msg"=>"购买成功"]);
            }else{
                return json(["code"=>0,"data"=>$res,"msg"=>"购买失败"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取饿了么geteleauth
     */
    public function geteleauth(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $config=new Config(\config("elekey"),\config("elesecret"),true);
            $client=new OAuthClient($config);
            $auth_url=$client->get_auth_url(request()->post("shopid"),"all","http://fuzzyy.wicp.net/index.php/index/Common/elecallback");
            return json(["code"=>1,"data"=>$auth_url,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 查询饿了么授权?
     */
    public function queryeleauth(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $elelink=new Elelink();
            $res=$elelink->where("shopid",request()->post("shopid"))->where("updatetime+expiresin>".time())->find();
            if($res){
                return json(["code"=>1,"data"=>"","msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户TOKEN不存在"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 查询美团授权
     */
    public function querymtauth(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $mtmodel=new \app\api\model\Meituan();
            $res=$mtmodel->where("shopid",request()->post("shopid"))->whereNotNull("token")->find();
            if($res&&$res["epoiid"]){
                return json(["code"=>1,"data"=>"","msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户TOKEN不存在"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 查询点评授权
     */
    public function querydpauth(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $mtmodel=new \app\api\model\Meituan();
            $res=$mtmodel->where("shopid",request()->post("shopid"))->whereNotNull("tuantoken")->find();
            if($res&&$res["epoiid"]){
                return json(["code"=>1,"data"=>"","msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户TOKEN不存在"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取饿了么营业统计数据
     */
    public function getelesta(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $elelink=new Elelink();
            $res=$elelink->where("shopid",request()->post("shopid"))->where("updatetime+expiresin>".time())->find();
            if($res){
                $yesterday=date("Y-m-d",strtotime("-1 day",time()));//昨日
                $eve=date("Y-m-d",strtotime("-2 day",time()));//前日
                $orddata=[];
                $eleorder=new Eleorder();
                $orddata["yesmoney"]=$eleorder->whereIn("shopid",$res["authorizedshops"])->where("status","settled")->whereLike("createdat",$yesterday."%")->sum("totalprice");
                $orddata["yescount"]=$eleorder->whereIn("shopid",$res["authorizedshops"])->where("status","settled")->whereLike("createdat",$yesterday."%")->count();
                $orddata["evemoney"]=$eleorder->whereIn("shopid",$res["authorizedshops"])->where("status","settled")->whereLike("createdat",$eve."%")->sum("totalprice");
                $orddata["evecount"]=$eleorder->whereIn("shopid",$res["authorizedshops"])->where("status","settled")->whereLike("createdat",$eve."%")->count();
                return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户TOKEN不存在"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获得美团外卖一天的收入和订单列表
     */
    public function getmtoneday(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $mtmodel=new \app\api\model\Meituan();
            $res=$mtmodel->where(["shopid"=>request()->post("shopid")])->find();
            if($res){
                $orddata=[];
                $jdorder=model("Jdorder");
                $selectday=!input("post.selectday")?date("Y-m-d"):input("post.selectday");//默认为今天
                $orddata["dateformat"]=date("m月d日",strtotime($selectday));
                //总金额 总单数
                $orddata["totalfee"]=$jdorder->where("producestationno='".$res["epoiid"]."' and orderstatus=33060 and platform=2 and orderstarttime like '$selectday%'")->sum("ordertotalmoney");;
                $orddata["totalnum"]=$jdorder->where("producestationno='".$res["epoiid"]."' and orderstatus=33060 and platform=2 and orderstarttime like '$selectday%'")->count();
                //订单列表
                $orddata["lists"]=$jdorder->where("producestationno='".$res["epoiid"]."' and orderstatus=33060 and platform=2 and orderstarttime like '$selectday%'")->select();
                return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"暂无门店"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取美团营业统计数据
     */
    public function getmtsta(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $mtlink=new \app\api\model\Meituan();
            //TODO 下句需要重写
            $res=$mtlink->where("shopid",request()->post("shopid"))->find();
            if($res){
                //TODO 以下逻辑需要重写
                $yesterday=date("Y-m-d",strtotime("-1 day",time()));//昨日
                $eve=date("Y-m-d",strtotime("-2 day",time()));//前日
                $orddata=[];
                $mtorder=new Jdorder();
                $orddata["yesmoney"]=$mtorder->whereIn("producestationno",$res["epoiid"])->where("orderstatus","33060")->whereLike("orderstarttime",$yesterday."%")->sum("ordertotalmoney");
                $orddata["yescount"]=$mtorder->whereIn("producestationno",$res["epoiid"])->where("orderstatus","33060")->whereLike("orderstarttime",$yesterday."%")->count();
                $orddata["evemoney"]=$mtorder->whereIn("producestationno",$res["epoiid"])->where("orderstatus","33060")->whereLike("orderstarttime",$eve."%")->sum("ordertotalmoney");
                $orddata["evecount"]=$mtorder->whereIn("producestationno",$res["epoiid"])->where("orderstatus","33060")->whereLike("orderstarttime",$eve."%")->count();
                return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"用户TOKEN不存在"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取美团营业统计数据
     */
    public function getmtdetail(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
                $orddata=[];
                $mtorder=new Jdorder();
                $orddata["basic"]=$mtorder->where("orderid",input("post.orderid"))->where("platform",2)->find();
                if(empty($orddata["basic"])){
                    return json(["code"=>0,"data"=>"","msg"=>"订单不存在"]);
                }
                $orddata["orderdetail"]=model("jdorderdetail")->where("pid",$orddata["basic"]["id"])->select();
                return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获得美团昵称和营业状态
     */
    public function getmtnick(){
         if(request()->post("shopid")){
             $res=model("meituan")->where("shopid",request()->post("shopid"))->find();
             if(!isset($res["epoiid"])){
                 return json(["code"=>0,"data"=>"","msg"=>"no shop"]);
             }
             $ePoiId=$res['epoiid'];
             $token=$res['token'];
             $time=time();
             $url="http://api.open.cater.meituan.com/waimai/poi/queryPoiInfo?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiIds=$ePoiId";
             $signKey=model("meituan")->SignKey($url);
             $url=$url."&sign=".$signKey;
             $json=curl_get($url);
             $data=json_decode($json,true);
             return json(["code"=>1,"data"=>$data,"msg"=>"ok"]);
         }else{
             return json(["code"=>0,"data"=>"","msg"=>"error"]);
         }
    }

    /**
     * 根据日期查询门店验券历史
     * 2017年4月14日 15:24:10
     * @link  http://developer.meituan.com/openapi#5.6
     */
    public function querytgbydate(){
        $userid=self::verifytoken(request()->post("token"));
        if(!$userid){
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
        $res=model("meituan")->where("shopid",request()->post("shopid"))->find();
        if(!isset($res["epoiid"])){
            return json(["code"=>0,"data"=>"","msg"=>"no shop"]);
        }
        if(empty($res["tuantoken"])){
            return json(["code"=>0,"data"=>"","msg"=>"no bind"]);
        }
        $appAuthToken=$res["tuantoken"];
        $history=[];
        $offset=0;
        //开始迭代
        do{
            $date=request()->post("selectday");
            $time = time();
            $url = "http://api.open.cater.meituan.com/tuangou/coupon/queryListByDate?appAuthToken=$appAuthToken&charset=UTF-8&timestamp=$time&date=$date&offset=$offset&limit=50";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
//            dump($res);
            $offset+=50;
            if(isset($res["data"]["couponCodes"]))$history=array_merge($history,$res["data"]["couponCodes"]);
        }while(isset($res["data"]["total"])&&$res["data"]["total"]!=0);
        return json(["code"=>1,"data"=>$history,"msg"=>"success"]);
    }


    /**
     *根据日期查询门店闪惠历史
     * @link http://developer.meituan.com/openapi#6.3
     */
    public function queryshdate(){
        $userid=self::verifytoken(request()->post("token"));
        if(!$userid){
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
        $res=model("meituan")->where("shopid",request()->post("shopid"))->find();
        if(!isset($res["epoiid"])){
            return json(["code"=>0,"data"=>"","msg"=>"no shop"]);
        }
        if(empty($res["tuantoken"])){
            return json(["code"=>0,"data"=>"","msg"=>"no bind"]);
        }
        $appAuthToken=$res["tuantoken"];
        $history=[];
        $page=1;
        //开始迭代
        do{
            $date=request()->post("selectday");
            $time = time();
            $url = "http://api.open.cater.meituan.com/shanhui/order/queryListByEpoiId?date=$date&page=$page&pageSize=20&appAuthToken=$appAuthToken&timestamp=$time&charset=utf-8";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
//            dump($res);
            $page++;
            if(isset($res["data"]["orderDTOs"]))$history=array_merge($history,$res["data"]["orderDTOs"]);
        }while(isset($res["data"]["totalPageCount"])&&($page<=$res["data"]["totalPageCount"]));
        return json(["code"=>1,"data"=>$history,"msg"=>"success"]);
    }

    /**
     * 获得某用户的饿了么门店列表
     */
    public function geteleshop(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $linkinfo=model("elelink")->where("shopid",request()->post("shopid"))->find();
            $config=new Config(\config("elekey"),\config("elesecret"),true);
            $token=unserialize($linkinfo["serializetoken"]);
            $authorizedshops=explode(",",$linkinfo["authorizedshops"]);
            $shop_service=new ShopService($token,$config);
            $data=[];
            foreach ($authorizedshops as $k=>$v){
                $result=$shop_service->get_shop((float)$v);
                if(!$result){
                    continue;
                }
                $data[]=[
                    "eleid"=>$result->id,
                    "shopname"=>$result->name
                ];
            }
            return json(["code"=>1,"data"=>$data,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 获取饿了么营业统计数据
     */
    public function geteleoneday(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
                $elemodel=new Eleorder();
                $orddata=[];
                $selectday=!input("post.selectday")?date("Y-m-d"):input("post.selectday");//默认为今天
                //总金额 总单数
                $orddata["totalfee"]=$elemodel->whereIn("shopid",input("post.eleid"))->where("status","settled")->whereLike("createdat",$selectday."%")->sum("totalprice");;
                $orddata["totalnum"]=$elemodel->whereIn("shopid",input("post.eleid"))->where("status","settled")->whereLike("createdat",$selectday."%")->count();
                //订单列表
                $res=$elemodel->whereIn("shopid",input("post.eleid"))->where("status","settled")->whereLike("createdat",$selectday."%")->select();
                $orddata["lists"]=[];
                foreach ($res as $k=>$v){
                    $orddata["lists"][]=[
                        "id"=>$v["id"],
                        "orderid"=>$v["orderid"],
                        "phonelist"=>unserialize($v["phonelist"]),
                        "createdat"=>$v["createdat"],
                        "status"=>$v["status"],
                        "daysn"=>$v["daysn"],
                        "consignee"=>$v["consignee"],
                        "originalprice"=>$v["originalprice"],
                        "deliverypoiaddress"=>$v["deliverypoiaddress"]
                    ];
                }
                return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    public function geteledetail(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $elemodel=new Eleorder();
            $res=$elemodel->where("orderid",request()->post("orderid"))->find();
            if($res){
                $res["phonelist"]=unserialize($res["phonelist"]);
                $res["groups"]=unserialize($res["groups"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"empty data"]);
            }
            return json(["code"=>1,"data"=>$res,"msg"=>"success"]);
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }


    /**
     * 获得点评门店的2天的营业状态
     */
    public function getdpsta(){
        set_time_limit(300);
        $userid=self::verifytoken(request()->post("token"));
        if(!$userid){
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
        $res=model("meituan")->where("shopid",request()->post("shopid"))->find();
        if(!isset($res["epoiid"])){
            return json(["code"=>0,"data"=>"","msg"=>"no shop"]);
        }
        if(empty($res["tuantoken"])){
            return json(["code"=>0,"data"=>"","msg"=>"no bind"]);
        }
        $appAuthToken=$res["tuantoken"];
        $yesterday=date("Y-m-d",strtotime("-1 day",time()));//昨日
        $eve=date("Y-m-d",strtotime("-2 day",time()));//前日

        $history=[];
        $offset=0;
        //开始迭代昨天团购数据
        do{
            $time = time();
            $url = "http://api.open.cater.meituan.com/tuangou/coupon/queryListByDate?appAuthToken=$appAuthToken&charset=UTF-8&timestamp=$time&date=$yesterday&offset=$offset&limit=50";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
            $offset+=50;
            if(isset($res["data"]["couponCodes"]))$history=array_merge($history,$res["data"]["couponCodes"]);
        }while(isset($res["data"]["total"])&&$res["data"]["total"]!=0);
        $tmp=self::parseTg($history);
        $orddata["yesmoney"]=$tmp["money"];
        $orddata["yescount"]=$tmp["count"];

        $history=[];
        $offset=0;
        //开始迭代前天团购数据
        do{
            $time = time();
            $url = "http://api.open.cater.meituan.com/tuangou/coupon/queryListByDate?appAuthToken=$appAuthToken&charset=UTF-8&timestamp=$time&date=$eve&offset=$offset&limit=50";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
            $offset+=50;
            if(isset($res["data"]["couponCodes"]))$history=array_merge($history,$res["data"]["couponCodes"]);
        }while(isset($res["data"]["total"])&&$res["data"]["total"]!=0);
        $tmp=self::parseTg($history);
        $orddata["evemoney"]=$tmp["money"];
        $orddata["evecount"]=$tmp["count"];

        $history=[];
        $page=1;
        //开始迭代昨天闪惠数据
        do{
            $time = time();
            $url = "http://api.open.cater.meituan.com/shanhui/order/queryListByEpoiId?date=$yesterday&page=$page&pageSize=20&appAuthToken=$appAuthToken&timestamp=$time&charset=utf-8";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
            $page++;
            if(isset($res["data"]["orderDTOs"]))$history=array_merge($history,$res["data"]["orderDTOs"]);
        }while(isset($res["data"]["totalPageCount"])&&($page<=$res["data"]["totalPageCount"]));
        $tmp=self::parseSh($history);
        $orddata["evemoney"]+=$tmp["money"];
        $orddata["evecount"]+=$tmp["count"];

        $history=[];
        $page=1;
        //开始迭代前天闪惠数据
        do{
            $time = time();
            $url = "http://api.open.cater.meituan.com/shanhui/order/queryListByEpoiId?date=$eve&page=$page&pageSize=20&appAuthToken=$appAuthToken&timestamp=$time&charset=utf-8";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json =curl_get($url);
            $res=json_decode($json,true);
            $page++;
            if(isset($res["data"]["orderDTOs"]))$history=array_merge($history,$res["data"]["orderDTOs"]);
        }while(isset($res["data"]["totalPageCount"])&&($page<=$res["data"]["totalPageCount"]));
        $tmp=self::parseSh($history);
        $orddata["evemoney"]+=$tmp["money"];
        $orddata["evecount"]+=$tmp["count"];

        return json(["code"=>1,"data"=>$orddata,"msg"=>"success"]);//返回2天的营业状况
    }


    /**
     * 获得点评一天的数据
     */
    public function getdponeday(){
        //TODO
    }


    /**
     * 格式化美团团购订单数据
     * @param $orders
     */
    private static function parseTg($orders){
        $back["money"]=0;
        $back["count"]=0;
        if(is_array($orders)){
            foreach ($orders as $k=>$v){
                $back["money"]+=(real)$v["dealValue"];
                $back["count"]++;
            }
        }
        return $back;
    }

    /**
     * 格式化美团闪惠订单数据
     * @param $orders
     */
    private static function parseSh($orders){
        $back["money"]=0;
        $back["count"]=0;
        if(is_array($orders)){
            foreach ($orders as $k=>$v){
                $back["money"]+=(real)$v["userPayAmount"];
                $back["count"]++;
            }
        }
        return $back;
    }

    /**
     * 用户修改密码
     */
    public function modifypwd(){
        $userid=self::verifytoken(request()->post("token"));
        if($userid){
            $res=model("manager")->save([
                "password"=>md5(request()->post("password"))
            ],["id"=>$userid]);
            if($res){
                return json(["code"=>1,"data"=>"","msg"=>"修改成功"]);
            }else{
                return json(["code"=>0,"data"=>"","msg"=>"修改失败"]);
            }
        }else{
            return json(["code"=>-1,"data"=>"","msg"=>"用户鉴权失败"]);
        }
    }

    /**
     * 发送验证码
     */
    public function sendverify(){
        if (!isMobiles(input("post.phone"))) {
            return json(["code"=>0,"data"=>"","msg"=>"手机号不合法"]);
        }
        $data = array('text' => "您的验证码是" . input("post.code"), 'apikey' => \config("yunapikey"), 'mobile' => input("post.phone"));
        $json_data = sendsms($data);
        if ($json_data['code'] == 0) {
            return json(["code"=>1,"data"=>"","msg"=>"短信已发送"]);
        } else {
            return json(["code"=>0,"data"=>"","msg"=>"短信发送失败,请稍后再试"]);
        }
    }


}
